<?php

/*
Quad_Debug
Copyright (c) 2009 Ken Snyder
http://code.google.com/p/quadphp

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/**
 * Pretty print variables to an appropriate place 
 */
class Quad_Debug {
	
	public static function enabled() {
		$disabled = (defined('QUAD_DEBUG_DISABLE') && QUAD_DEBUG_DISABLE);
		return !$disabled;
	}
	
	public static function log() {
		if (!self::enabled()) return;

		ob_start();
		self::_dump(func_get_args());
		$html = ob_get_clean();
		
		$html = preg_replace('~<style.*</style>~s',"", $html);
		$html = str_replace('&ldquo;','"', $html);
		$html = str_replace('&rdquo;','"', $html);
		$html = str_replace('&nbsp;'," ", $html);
		$html = str_replace('<br>',"\n", $html);
		
		$str = strip_tags($html);
		$str = html_entity_decode($str);
		$str = trim($str);
		error_log($str);
	}
	
	public static function getDump($args) {
		foreach ($args as &$a) {
			if (is_object($a)) {
				$a = self::getObjectDump($a);
			}
			else {
				$a = self::getGeneralDump($a);
			}
		}
		return $args;		
	}
	
	public static function dump() {
		if (!self::enabled()) return;
		
		self::_dump(func_get_args());
	}
	
	public static function dumpdie() {
		if (!self::enabled()) return;
		
		self::_dump(func_get_args());
		die();
	}
	
	protected static function _formatArgs($args) {
		if (count($args) == 1) {
			$args = $args[0];
		}
		else {
			$newArgs = array();
			foreach ($args as $i => $a) {
				$newArgs["@arg$i"] = $a;
			}
			$args = $newArgs;
		}
		return $args;		
	}
	
	protected static function _dump($args) {
//		echo '<pre>';
//		var_dump($args);
//		return;
		static $cssPrinted = 0;
		$bt = debug_backtrace();
		$bt = array_slice($bt,1);
		$file = str_replace($_SERVER['DOCUMENT_ROOT'].'/','',$bt[0]['file']);
		$line = $bt[0]['line'];
		$args = self::_formatArgs($args);
		if ($cssPrinted++ == 0) {
			echo '<style type="text/css" media="screen">
pre.ppr {
	font-family: "Bitstream Vera Sans Mono", Consolas, "Times New Roman", monospace;
	font-size: 12px;
	line-height: 130%;
	word-wrap: break-word; /* IE 5.5 - 7 */
	white-space: pre-wrap; /* IE8, EOMB */
	background-color: rgba(255,255,255,0.92);
	background-color: rgb(255,255,255);
	border: 1px solid #888;
	padding: 5px;
	text-align: left;
	clear: both;
}
.ppr-array,
.ppr-object,
.ppr-resource {
	font-style: italic;
}
.ppr-brace,
.ppr-parens {
	font-style: normal;
}
.ppr-string {
	color: #008800;
	font-weight: normal;
}
.ppr-lquot {
	color: #777;
	font-family: "Times New Roman", Times, serif;
	font-weight: bold;
	font-size: 10px;
	margin-right: 2px;
}
.ppr-rquot {
	color: #777;
	font-family: "Times New Roman", Times, serif;
	font-weight: bold;
	font-size: 10px;
	margin-left: 2px;
}	
.ppr-arrow {
	color: #777;
	font-weight: bold;
}
.ppr-array-key {
	color: #303030;
	font-weight: normal;
}
.ppr-class,
.ppr-resource-type {
	color: #0055ee;
	font-weight: bold;
	font-style: normal;
}	
.ppr-null {
	color: #0000ee;
	font-style: italic;
}
.ppr-bool {
	color: #dd7700;
	font-style: italic;
}
.ppr-bracket {
	color: #888;
}
.ppr-float {
	color: #2200ee;
	font-weight: bold;		
}
.ppr-int {
	color: #cc0000;
	font-weight: bold;		
}
.ppr-max {
	text-transform: uppercase;
	font-style: italic;
	color: #bb6666;
	font-weight: bold;
}
</style>';
		}		
		echo "\n<pre class=\"ppr\">Quad_Debug dump: $file($line)\n";
		echo self::prettyPrint($args);
		echo "</pre>";
	}

	public static function prettyPrint($val,$_maxDepth=16,$_level=0,$_isInObject=false,&$_objIdCache=array()) {
		$indentPrev = ($_level > 0 ? str_repeat('&nbsp;&nbsp;&nbsp;',$_level-1) : '');
		$indent = str_repeat('&nbsp;&nbsp;&nbsp;',$_level);
		$indentNext = str_repeat('&nbsp;&nbsp;&nbsp;',$_level+1);
		$out = '';
		if ($val === false || $val === true) {
			$out .= '<span class="ppr-bool">' . ($val ? 'true' : 'false') . '</span>';
		}
		elseif ($val === null) {
			$out .= '<span class="ppr-null">null</span>';
		}
		elseif (is_resource($val)) {
			ob_start();
			var_dump($val);
			$dump = ob_get_clean();
			preg_match('/^.+\((\d+)\) of type \(([\w_ ]+)\)$/',$dump,$match);
			$out .= '<span class="ppr-resource">Resource #' . $match[1] . ' <span class="ppr-resource-type">'.$match[2].'</span></span>';
		}
		elseif (is_array($val)) {
			if ($_maxDepth == 0) {
				$out .= '<span class="ppr-array">Array <span class="ppr-parens">(</span> <span class="ppr-max">Max Depth</span> <span class="ppr-parens">)</span></span>';
			}
			else {
				if (!$_isInObject) {
					$out .= '<span class="ppr-array">Array <span class="ppr-parens">(</span></span>' . "<br>";
				}
				foreach ($val as $k => $v) {
					$out .= $indentNext . '<span class="ppr-bracket">[<span class="ppr-array-key">' . htmlentities((string) $k,ENT_QUOTES,'utf-8') . '</span>]</span>';
					$out .= ' <span class="ppr-arrow">=&gt;</span> ' .  self::prettyPrint($v,$_maxDepth-1,$_level+1,false,$_objIdCache);
				}
				if (!$_isInObject) {
					$out .= $indent . '<span class="ppr-parens">)</span>';
				}
			}
		}
		elseif (is_object($val)) {
			ob_start();
			var_dump($val);
			$dump = ob_get_clean();		
			preg_match('/^\w+\(([\w_]+)\)#(\d+)/',$dump,$match);
			$class = $match[1];
			$id = $match[2];
			if ($_maxDepth <= 1 || isset($_objIdCache[$id])) {
				$text = (isset($_objIdCache[$id]) ? 'Recursion' : 'Max Depth');
				$out .= '<span class="ppr-object">Object #' . $id .' <span class="ppr-class">'.$class.'</span> <span class="ppr-brace">{</span> <span class="ppr-max">'.$text.'</span> <span class="ppr-brace">}</span></span>';
			}
			else {
				$_objIdCache[$id] = 1;
				
				$props = self::getObjectDump($val, $dump);			
				$out .= '<span class="ppr-object">Object #' . $id .' <span class="ppr-class">'.$class.'</span> <span class="ppr-brace">{</span></span>';
				if (count($props)) {
					$out .= "<br>";
					$out .= self::prettyPrint($props,$_maxDepth-1,$_level,true,$_objIdCache);
					$out .= $indent;
				}
				$out .= '<span class="ppr-brace">}</span>';
			}
		}
		elseif (is_float($val)) {
			$out .= '<span class="ppr-float">' . $val . '</span>';
		}
		elseif (is_int($val)) {
			$out .= '<span class="ppr-int">' . $val . '</span>';
		}
		else {
			$out .= '<span class="ppr-string"><span class="ppr-lquot">&ldquo;</span>' . htmlentities((string) $val,ENT_QUOTES,'utf-8') . '<span class="ppr-rquot">&rdquo;</span></span>';
		}
		if (!$_isInObject) {
			$out .= "<br>";
		}
		return $out;
	}
	
	public static function dumpRs($rs, $die = false) {
		if (!self::enabled()) return;
		$out = '';
		$out .= '<table class="ppr-rs" border="1">';
		$out .= Quad_Html::trs($rs, true);
		$out .= '</table>';
		echo $out;
		if ($die) {
			die();
		}
	}
	
	public static function getObjectDump($obj, $dump = '') {
		if (is_callable(array($obj, 'quadDebug'))) {
			return $obj->quadDebug($dump);
		}
		$props = get_object_vars($obj);
		return $props;
	}
	
	public static function getGeneralDump($val) {
		if (is_array($val)) {
			$val = self::getDump($val);
			return $val;
		}
		return $value;		
//		if ($val === false || $val === true) {
//			return ($val ? 'true' : 'false');
//		}
//		elseif ($val === null) {
//			return 'null';
//		}
//		elseif (is_float($val) || is_int($val)) {
//			return (string) $val;
//		}
//		elseif (is_array($val)) {
//			foreach ($val as &$v) {
//				self::getDump($v);
//			}
//			return $val;
//		}
//		return '"' . $value . '"';
	}
	
//	public function getObjectDump($obj, $dump = null) {
//		//return json_encode($obj);
//		if ($dump === null) {
//			ob_start();
//			var_dump($obj);
//			$dump = ob_get_clean();
//		}
//		preg_match_all('/  \["([^"]+):protected"\]=>\s+(?:bool\((true|false)\)|int\((\d+)\)|float\(([\d.e-]+)\)|string\(\d+\) "([^"]+)"|array\(\d+\) \{([^}]+?)\}|(NULL)|object)/', $dump, $matches, PREG_SET_ORDER);
//		$props = get_object_vars($obj);
//return $props;
//		foreach ($matches as $match) {
//			if ($match[2]) {
//				$val = ($match[2] == 'true');
//			}
//			elseif ($match[3]) {
//				$val = (int) $match[3];
//			}
//			elseif ($match[4]) {
//				$val = (float) $match[4];
//			}
//			elseif ($match[5]) {
//				$val = (string) $match[5];
//			}
//			elseif ($match[6]) {
//				// array TODO
//				$val = (string) $match[6];
//			}
//			elseif ($match[7]) {
//				$val = null;
//			}							
//			elseif ($match[8]) {
//				// object TODO
//				$val = (string) $match[8];
//			}				
//			$props[$match[1]] = $val;
//		}
//		return $props;
//	}
	
}